import _ from 'lodash';
import moment from 'moment';
import { customKeys } from './constant';

export const getExportList = (data = []) => {
  let arr = [];
  const fun = (list) => {
    list.forEach((i) => {
      arr.push(i);
      if (i?.children instanceof Array) {
        fun(i.children);
      }
    });
  };
  fun(data);
  return arr;
};

/**
 * 表格
 */
export const CODE1 = 'title';
export const tableColumns = [
  {
    code: CODE1,
    name: '聚合维度',
    width: 158,
    lock: true,
  },
  {
    name: '结算单电量(MWh)',
    code: 'settleManageQuantity',
    align: 'center',
    width: 125,
  },
  {
    name: '绿证交易绿证数(个)',
    code: 'greenCertificateNum',
    align: 'center',
    width: 125,
  },
  {
    name: '理论生产总量(个)',
    code: 'theoreticalTotalProduction',
    align: 'center',
    width: 125,
  },
  {
    name: '核发绿证(个)',
    code: 'issuingGreenCertificates',
    align: 'center',
    width: 125,
  },
  {
    name: '已售绿证(个)',
    code: 'greenCertificatesSold',
    align: 'center',
    width: 125,
  },
  {
    name: '实际库存绿证(个)',
    code: 'actualInventoryGreenCertificate',
    align: 'center',
    width: 125,
  },
];
const columsMap = {
  聚合维度: CODE1,
  '结算单电量(MWh)': 'settleManageQuantity',
  '绿证交易绿证数(个)': 'greenCertificateNum',
  '理论生产总量(个)': 'theoreticalTotalProduction',
  '核发绿证(个)': 'issuingGreenCertificates',
  '已售绿证(个)': 'greenCertificatesSold',
  '实际库存绿证(个)': 'actualInventoryGreenCertificate',
};
export const getTableData = (_data, _order) => {
  const { data, head } = _data || {};
  if (!_data || _.isEmpty(data) || _.isEmpty(head))
    return {
      tableData: [],
      exportTable: [],
    };
  // 数据处理
  const fmtRow = (_row, _title, _tag) => {
    let res = {
      id: _.uniqueId(),
      [CODE1]: _title,
    };
    head.map((k, i) => {
      let val = _row[i];
      val = parseFloat(val).toFixed(['结算单电量(MWh)'].includes(k) ? 3 : 0);
      res[columsMap[k]] = val;
    });
    return res;
  };
  // 递归种一颗树
  let exportTable = []; // 导出用
  const fn = ({ total, ...list }, title, lv) => {
    let result = fmtRow(total, title, _order[lv - 1]);
    exportTable.push(result);
    let children = [];
    for (const k in list) {
      let temp = {};
      if (!!list[k]?.length) {
        temp = fmtRow(list[k], k, _order[lv]);
        exportTable.push(temp);
      } else {
        temp = fn(list[k], k, lv + 1);
      }
      children.push(temp);
    }
    if (!!children.length) {
      result.children = children.sort((a, b) => {
        if (['年份', '月份'].includes(_order[lv])) {
          return a[CODE1] - b[CODE1];
        }
        return a[CODE1].localeCompare(b[CODE1], 'zh-CN');
      });
    }
    return result;
  };
  // 总合计要单独一行
  const { children, ...total } = fn(data, '合计', 0);
  const tableData = [total, ...(children || [])];
  return { tableData, exportTable };
};

//需要展示双Y轴的图表
const Doubel_yAxis_title = ['绿证申请情况', '绿证销售情况'];
//需要展示双Y轴的serise字段
const Doubel_yAxis_serise = ['environmentalProductivity', '_computerData'];
const indexMap = {
  netEnvironmentalProductionTotal: {
    name: '净环保生产总量',
    type: 'bar',
    color: '#2174FF',
  },
  environmentalProductivity: {
    name: '环保生产率',
    type: 'bar',
    color: '#3CB1FB',
  },
  issuingGreenCertificates: {
    name: '核发绿证数',
    type: 'line',
    color: '#2174FF',
  },
  actualInventoryGreenCertificate: {
    name: '实际库存绿证',
    type: 'line',
    color: '#3CB1FB',
  },
  _computerData: {
    name: '周转率',
    type: 'line',
    color: '#3CB1FB',
  },
};

const borderColor = '#4E5154'; // 分割线/分割线&边框
const fontColor1 = '#D3D4D4'; // 文本颜色/一级文本
const fontColor2 = '#A7A8A9'; // 文本颜色/二级文本
const fontColor3 = '#7A7D7F'; // 文本颜色/三级文本
const formatter = (params) => {
  let content = [];
  params.map((x) => {
    const { marker, seriesName, dimensionNames, encode, data, axisIndex } = x;
    let value = typeof data === 'object' ? data[dimensionNames[encode.y[0]]] : data;
    value = value + (['环保生产率', '未指定名称'].includes(seriesName) ? '%' : ''); //百分号展示
    if (typeof value === 'undefined') value = '-';
    if (!content[axisIndex]) content[axisIndex] = '';
    content[axisIndex] += `<div style="display:flex;align-items:center;">${marker}
                            <div style="flex:1;display:flex;align-items:center;justify-content:space-between;">
                              <span style="color:${fontColor2};">${seriesName}</span>
                              <span style="color:${fontColor1};margin-left:8px;">${value}</span>
                            </div>
                          </div>`;
  });
  const sline = `<div style="width:100%;height:1px;background:${borderColor};margin:4px 0"></div>`;
  return `<div style="color:${fontColor3};">${params?.[0]?.axisValue || ''}</div>
          <div>${content.join(sline)}</div>`;
};

/**图表配置*/
export const getChartOption = ([title, data], dataSource) => {
  const hasNegative = dataSource.find((t) => data.find((key) => t[key] < 0));
  const symmetry = {
    max: (value) => {
      const { max, min } = value;
      const absMax = Math.max(Math.abs(max), Math.abs(min));
      return absMax;
    },
    min: (value) => {
      const { max, min } = value;
      const absMax = Math.max(Math.abs(max), Math.abs(min));
      return -absMax;
    },
  };
  const _yAxis = [
    {
      type: 'value',
      splitLine: { show: false },
      name: '（个）',
      nameTextStyle: {
        align: 'right',
      },
      ...(hasNegative ? symmetry : {}),
    },
    {
      type: 'value',
      name: '（%）',
      nameTextStyle: {
        align: 'left',
      },
      ...(hasNegative ? symmetry : {}),
    },
  ];

  const _series = data.map((t) => {
    let { props, ...others } = _.cloneDeep(indexMap[t]);
    if (Doubel_yAxis_title.includes(title) && Doubel_yAxis_serise.includes(t)) {
      props = { ...props, yAxisIndex: 1 };
    }
    return {
      dataIndex: t,
      props,
      ...others,
    };
  });
  return {
    grid: { top: 30, left: 28, right: 28, bottom: 72, containLabel: true },
    series: _series,
    dataset: {
      source: dataSource,
      dimensions: [CODE1, ...data],
    },
    tooltip: {
      formatter,
    },
    dataZoomSlider: true,
    legend: {},
    xAxis: [{ type: 'category' }],
    yAxis: _yAxis,
  };
};

export const initParam = (param) => {
  const obj = {
    // startMonth: moment(param?.startMonth).startOf('year').format('YYYY-MM-DD'),
    // endMonth: moment(param?.endMonth).endOf('year').format('YYYY-MM-DD'),
    // environmentalType: ['海上', '陆上'], //当前未进行环境类型 传全部
  };
  [
    'stationName',
    // 'beiJiaoSuo',
    // 'chinaGreenCertificate',
    // 'projectType',
    // 'startMonth',
    // 'endMonth',
    // 'environmentalType',
    // 'guangJiaoSuo',
    // 'renewable',
    // 'subsidizeType',
    // 'whiteList',
  ].forEach((item) => {
    if (customKeys.includes(item)) {
      obj[item] = [decodeURIComponent(param?.[item]) == '1' ? '已办完' : '未办完'];
      return;
    }

    if (!param?.[item]) return;
    obj[item] = [decodeURIComponent(param?.[item])];
  });
  return obj;
};

export const getFilterList = (power, initValues) => {
  let filterList = [
    {
      label: '日期',
    },
  ];
  if (!_.isEmpty(initValues)) {
    filterList[0].moments = [moment(initValues.startMonth), moment(initValues.endMonth)];
    filterList[0].value = [initValues.startMonth, initValues.endMonth];
  }

  let stationlist = [];
  if (power.length > 0) {
    let obj = {
      label: '场站',
      list: [],
      hasSearch: true,
      value: initValues.stationName,
    };
    power.map((x) => {
      // 场站
      let label = x.label == '全省' ? x.provinceName + '-' + x.label : x.label;
      const temp = {
        label,
        value: x.value,
      };
      stationlist.push(temp);
      obj.list.push(label);
    });
    filterList.unshift(obj);
  }
  return { stationlist, filterList };
};

export const computerData = (t) => {
  const parse = (data, len = 3) => parseFloat(data).toFixed(len);

  const netEnvironmentalProductionTotal = parse(
    t.theoreticalTotalProduction - t.issuingGreenCertificates,
  );
  const environmentalProductivity = parse(
    ((t.theoreticalTotalProduction - t.issuingGreenCertificates) / t.theoreticalTotalProduction) *
      100,
    1,
  );
  const _computerData = t.greenCertificatesSold / t.issuingGreenCertificates;
  const obj = {
    netEnvironmentalProductionTotal: netEnvironmentalProductionTotal,
    environmentalProductivity,
    _computerData: _computerData || _computerData == 0 ? parse(_computerData * 100, 1) : '-',
  };

  return obj;
};
